#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

#define FILE_PATH "students.dat"
#define NUM_STUDENTS 5

typedef struct {
    char name[4];
    int age;
} Student;

int main() {
    int fd;
    Student *students;
    const int size = NUM_STUDENTS * sizeof(Student);

    // 打开文件
    if ((fd = open(FILE_PATH, O_RDONLY)) == -1) {
        perror("open failed");
        exit(EXIT_FAILURE);
    }

    // 映射文件到内存
    students = (Student*)mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
    if (students == MAP_FAILED) {
        perror("mmap failed");
        close(fd);
        exit(EXIT_FAILURE);
    }

    // 读取并显示数据
    printf("\nStudent List:\n");
    for (int i = 0; i < NUM_STUDENTS; i++) {
        printf("Name: %-4s Age: %d\n", students[i].name, students[i].age);
    }

    // 清理资源
    munmap(students, size);
    close(fd);
    return 0;
}
